package com.ruoyi.tenant.service.impl;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.tenant.common.BusinessException;
import com.ruoyi.tenant.entity.SysDeptEntity;
import com.ruoyi.tenant.mapper.SysDeptDao;
import com.ruoyi.tenant.service.SysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("sysDeptService")
public class SysDeptServiceImpl implements SysDeptService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SysDeptDao sysDeptDao;
	
	@Override
	public SysDeptEntity queryObject(Long deptId){
		return sysDeptDao.queryObject(deptId);
	}
	
	@Override
	public List<SysDeptEntity> queryList(Map<String, Object> map){
		return sysDeptDao.queryList(map);
	}
	
	@Override
	public void save(SysDeptEntity sysDept){
		
		if (sysDept.getBusinessId() == null) {
			// 设置商户id
			try {
				sysDept.setBusinessId(this.findBusinessId(sysDept.getParentId()));
			} catch (BusinessException ex) {
				logger.error("商户ID设置失败", ex);
				throw ex;
			}
		}
		
		sysDeptDao.save(sysDept);
	}
	
	/**
	 * @Description: 查询指定部门的商户ID
	 * @param parentId void
	 */
	private Integer findBusinessId(Long parentId) {
		
		SysDeptEntity sysDeptEntity = this.queryObject(parentId);
		if (sysDeptEntity != null && sysDeptEntity.getParentId() == 1 && sysDeptEntity.getBusinessId() != null) {
			return sysDeptEntity.getBusinessId();
		} else if (sysDeptEntity != null && sysDeptEntity.getParentId() == 1 && sysDeptEntity.getBusinessId() == null) {
			
			throw new BusinessException("商户ID取得失败！");
		} else {
			return this.findBusinessId(sysDeptEntity.getParentId());
		}
		
	}

	@Override
	public void update(SysDeptEntity sysDept){
		sysDeptDao.update(sysDept);
	}
	
	@Override
	public void delete(Long deptId){
		sysDeptDao.delete(deptId);
	}

	@Override
	public List<Long> queryDetpIdList(Long parentId) {
		return sysDeptDao.queryDetpIdList(parentId);
	}

	@Override
	public String getSubDeptIdList(Long deptId){
		//部门及子部门ID列表
		List<Long> deptIdList = new ArrayList<>();

		//获取子部门ID
		List<Long> subIdList = queryDetpIdList(deptId);
		getDeptTreeList(subIdList, deptIdList);

		//添加本部门
		deptIdList.add(deptId);

		String deptFilter = StringUtils.join(deptIdList, ",");
		return deptFilter;
	}

	/**
	 * 递归
	 */
	private void getDeptTreeList(List<Long> subIdList, List<Long> deptIdList){
		for(Long deptId : subIdList){
			List<Long> list = queryDetpIdList(deptId);
			if(list.size() > 0){
				getDeptTreeList(list, deptIdList);
			}

			deptIdList.add(deptId);
		}
	}
}
